package edu.pitt.cs3530.scripts;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class GetTotalWattage {
	public static void main(String args[]) {
		File directory = new File(args[0]);
		int time = 0;
		boolean hasTime = false;
		if (args.length > 1) {
			hasTime = true;
			time = Integer.parseInt(args[1]);
		}
		List<File> filesToProcess = new ArrayList<File>();
		if (directory.isDirectory()) {
			for (File file : directory.listFiles()) {
				filesToProcess.add(file);
			}
		} else {
			filesToProcess.add(directory);
		}
		for (File file : filesToProcess) {
			try {
				BufferedReader reader = new BufferedReader(new FileReader(file));
				double totalWattHours = 0.0;
				double lastTime = 0.0;
				while (reader.ready()) {
					String line = reader.readLine();
					if ((line != null) && (line.trim().length() > 0)) {
						StringTokenizer tok = new StringTokenizer(line, ",\t ");
						String token = tok.nextToken();
						if (!token.equalsIgnoreCase("Time")) {
							double t = Double.parseDouble(token);
							if (!hasTime || (hasTime && t > time)) {
							double wattage = Double
									.parseDouble(tok.nextToken());
							double percentOfMinute = 60.0 / 5;
								double wattHours = wattage / percentOfMinute / 60.0;
								
								totalWattHours += wattHours;
							}
						}
					}
				}
				System.out.println(file.getName() + ": ");
				System.out.println("\t" + totalWattHours);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
